<template>
  <a-upload
    :action="imgAction"
    :headers="uploadImgHeader"
    :file-list="fileList"
    :before-upload="beforeUpload"
    :data="data"
    :remove="handleRemove"
    @change="handleChange">
    <a-button>
      <a-icon type="upload" />选择文件
    </a-button>
  </a-upload>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { deleteFile } from '@/api/experiment'

const token = Vue.ls.get(ACCESS_TOKEN)
export default {
  props: {
    fileList: {
      type: Array,
      default: () => {
        return []
      }
    },
    data: {
      type: Object,
      default: () => {
        return {}
      }
    },
    //  0：课程封面1：实验封面2：实验笔记 3：实验数据4：实验答案
    module: {
      type: [String, Number],
      default: ''
    }
  },
  data () {
    return {
      imgAction: process.env.VUE_APP_API_BASE_URL + '/experiment/common/commonFile/upload',
      uploadImgHeader: {
        'Authorization': 'Bearer ' + token
      }
    }
  },
  methods: {
    // 验证文件大小
    beforeUpload (file) {
      const isImage = file.type.indexOf('image') !== -1
      if (!isImage) {
        this.$message.error('只能上传图片!')
        return false
      }
      const isLt10M = file.size / 1024 / 1024 < 5
      if (!isLt10M) {
        this.$message.error('文件大小不可超过 5MB!')
        return false
      }
      return isImage && isLt10M
    },
    // 监听文件删除
    handleRemove (file) {
      return deleteFile({ id: file.id }).then(res => {
        return true
      }).catch(() => {
        return false
      })
    },
    // 监听文件变化
    handleChange (info) {
      let fileList = [...info.fileList]
      fileList = fileList.map(file => {
        if (file.response) {
          const { path, domain, id } = file.response.content
          file.url = domain + path
          file.id = id
        }
        return file
      })
      // this.fileList = fileList
      this.updatedImgUrl(fileList)
    },
    updatedImgUrl (val) {
      this.$emit('updatedFileUrl', val)
    }
  }
}
</script>
